import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.DatagramSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wangxin
 * Date: 2024-08-12
 * Time: 20:42
 */
public class TCPEchoClient {
    private Socket socket = null;
    public TCPEchoClient(String serverIP,int serverPort) throws IOException {
        socket = new Socket(serverIP,serverPort);
    }
    public void start(){
        System.out.println("客户端启动！");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            Scanner scannerIn = new Scanner(System.in);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true){
                //1.从控制台读取数字
                System.out.print("->");
                String request = scannerIn.next();
                //2.把请求发给服务器
                printWriter.println(request);
                printWriter.flush();
                //3.从服务器读取响应
                String response = scanner.next();
                //4.打印响应结果
                System.out.println(response);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoClient client = new TCPEchoClient("127.0.0.1",9090);
        client.start();
    }
}
